<template>
   <div style="height:100%;">
      <div class='header-title'>
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>学院管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/collegeMana' }">学院信息管理</el-breadcrumb-item>
          <el-breadcrumb-item></el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!--数据筛选条件+按钮-->
      <el-row class='subjectMana filterForm' v-bind:style="{width: tableWidth + 'px'}">
        <el-form v-model="filterForm" ref="filterForm":inline="true">
          <el-form-item style="float:right">
            <el-button type="primary" @click="getCollegeListFro()" style="">查询</el-button>
            <el-button type="warning" :disabled="isAdmin" @click="addVisable = true" style="margin-right:15px">添加</el-button>
            <el-upload
              :disabled="isAdmin"
              class="upload-demo"
              ref="uploadExc"
              style="float:right"
              action=""
              :limit = "1"
              :http-request="uploadSubjectFro"
              :on-progress="onProgress"
              :before-upload = "beforeUploadExc"
              list-type="picture"
              accept="excel"
              :show-file-list="false">
              <el-button type="success" :disabled="isAdmin">批量导入</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
      </el-row>
      <!--表格数据-->
      <el-row style="margin-top:10px">
        <el-table
          v-loading="loading"
          :element-loading-text="loadingText"
          element-loading-spinner="el-icon-loading"
          :data="filterFormFro.tableData" 
          :border="true"
          :row-class-name="tableRowClassName"
          :header-cell-class-name = "tableHeaderClassName"
          v-bind:style="{width: tableWidth + 'px'}">
            <el-table-column prop="index" label="序号" sortable min-width="15%">
            </el-table-column>
            <el-table-column prop="college" label="学院名称" min-width="25%">
            </el-table-column>
            <el-table-column label="操作"  width="200">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  :disabled="isAdmin"
                  type="primary"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  size="mini"
                  :disabled="isAdmin"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
          </el-table-column>
        </el-table>
      </el-row>
      <!-- 添加学院信息弹窗 -->
      <el-dialog title="增加学院"  :visible.sync="addVisable"
          :closeOnClickModal="false"
          :close-on-click-modal="false" 
          :close-on-press-escape="false"
          width="550px"
          class="categoryManaDialog"
          @close="resetForm('addForm')">
        <el-form :model='addForm' ref="addForm" :rules="addRules">
            <!-- <el-form-item label="科类名称：" :label-width="formLabelWidth" prop="subjectId">
              <el-select
                v-model="addForm.subjectId"
                style='width:240px'
                placeholder="请选择科类" @change="(value) => getSubjectName(value, 'addForm')">
                <el-option
                  v-for="item in subjectList"
                  :key="item.subjectId"
                  :label="item.subjectName"
                  :value="item.subjectId">
                </el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item label="学院名称：" :label-width="formLabelWidth" prop="college">
              <el-input style='width:240px' clearable placeholder="请输入学院名称" v-model="addForm.college"></el-input>
            </el-form-item>
            <el-form-item label="" :label-width="formLabelWidth" >
              <el-button style="width:240px" type="primary" @click="submitAdd()">保 存</el-button>
            </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 编辑学院信息弹窗 -->
      <el-dialog title="编辑学院信息"   :visible.sync="editVisable"
          :closeOnClickModal="false" 
          width="550px"
          class="categoryManaDialog"
          :close-on-click-modal="false" 
          :close-on-press-escape="false"
          @close="resetForm('editForm')">
        <el-form :model='editForm' ref="editForm" :rules="editRules">
            <el-form-item label="学院名称：" :label-width="formLabelWidth" prop="college">
              <el-input style='width:300px' clearable v-model="editForm.college"></el-input>
            </el-form-item>
            <!-- <el-form-item label="科类名称：" :label-width="formLabelWidth" prop="subjectId">
              <el-select
                v-model="editForm.subjectId"
                style='width:300px'
                placeholder="请选择科类" @change="(value) => getSubjectName(value, 'editForm')">
                <el-option
                  v-for="item in subjectList"
                  :key="item.subjectId"
                  :label="item.subjectName"
                  :value="item.subjectId">
                </el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item label="" :label-width="formLabelWidth" >
              <el-button style="width:240px" type="primary" @click="submitEdit()">保 存</el-button>
            </el-form-item>
        </el-form>
      </el-dialog>
    </div>
</template>
<script>
import apiBus from '../../api/mainMana/api.js'
import apiFile from '../../api/apiFile/api.js'
import '../../../static/css/businessPlat/common.css'
import '../../../static/css/businessPlat/subjectMana.css'
export default {
  created () {
    sessionStorage.getItem('isAdmin') === 'false' ? this.isAdmin = false : this.isAdmin = true
    this.getSubjectListFro()
    this.getCollegeListFro() // 查询获得所有学院列表
  },
  data () {
    return {
      bigClassList: [], // 大类列表
      majorList: [], // 专业列表
      collegeList: [], // 学院列表
      subjectList: [], // 科类列表
      filterForm: { // 筛选表单
        subject: ''
      },
      isAdmin: true,
      filterFormFro: {
        tableData: [],
        allPages: 1
      },
      tableWidth: '', // 表格宽度
      loadingText: '正在拼命加载中，请稍等......',
      loading: false,
      paginationVisible: false, // 表格下方的分页显示
      noteVisible: false,
      formLabelWidth: '150px',
      addForm: { // 增加科目表单
        subjectId: '',
        college: '',
        bigClass: '',
        index: 0,
        major: ''
      },
      addVisable: false,
      editVisable: false,
      editForm: { // 编辑科目表单
        majorId: '',
        college: '',
        major: '',
        bigClass: '',
        subjectId: ''
      },
      deleteForm: { // 删除表单
        major: '',
        majorId: ''
      },
      addRules: {
        college: [
          { required: true, message: '请填写学院名称', trigger: 'blur' }
        ]
        /* subjectId: [
          { required: true, message: '请选择科类名称', trigger: 'blur' }
        ] */
      },
      editRules: {
        college: [
          { required: true, message: '请填写学院名称', trigger: 'blur' }
        ]
        /* subjectId: [
          { required: true, message: '请选择科类名称', trigger: 'blur' }
        ] */
      }
    }
  },
  methods: {
    /** ********************************* 页面处理数据格式等函数 ************************************************ */
    // 根据科类ID获得科类名字
    getSubjectName (value, form) {
      console.log('getSubjectName')
      this.subjectList.filter(item => {
        if (item.subjectId === value) {
          this[form].subjectName = item.subjectName
          return
        }
      })
    },
    // 根据科类名字获得科类ID
    getSubjectId (value, form) {
      console.log('getSubjectId')
      this.subjectList.filter(item => {
        if (item.subjectName === value) {
          this[form].subjectId = item.subjectId
          return
        }
      })
    },
    tableHeaderClassName ({row, column, rowIndex, columnIndex}) {
      if (rowIndex === 0) {
        return 'headerClass'
      }
    },
    tableRowClassName ({row, rowIndex}) {
      return 'rowClass'
    },
    // 点击表格中的“编辑”按钮
    handleEdit (index, row) {
      console.log(row)
      this.editVisable = true
      let data = this.filterFormFro.tableData[index]
      this.editForm.collegeId = data.collegeId
      this.editForm.college = data.college
      this.getSubjectId(data.subjectName, 'editForm')
      console.log('handleEdit')
      console.log(this.editForm)
    },
    // 点击表格中的“删除”按钮
    handleDelete (index, row) {
      let data = this.filterFormFro.tableData[index]
      this.deleteForm.collegeId = data.collegeId
      this.$confirm('确定删除该学院信息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteCollegeFro()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 重置表单
    resetError (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
      })
    },
    // 重置表单
    resetForm (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
      })
    },
    // 增加学院，点击“保存”
    submitAdd () {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.addCollegeFro()
        } else {
          return false
        }
      })
    },
    // 编辑专业信息，点击“保存”
    submitEdit () {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.editCollegeFro()
        } else {
          return false
        }
      })
    },
    // excel文件上传前进行检验格式
    beforeUploadExc (file) {
      console.log('上传的文件类型是：')
      console.log(file.type)
      /* const isExcel = file.type === 'application/vnd.ms-excel'
      if (!isExcel) {
        this.$message.warning('批量导入文件类型应为excel格式')
      } */
      return true
    },
    // 文件上传时
    onProgress (event, file, fileList) {
      this.loading = true
      console.log('文件正在上传')
      console.log(file)
    },
    /** ***************************** 向后台发送请求 ***************************************** */
    // 向后台发送信息批量导入科目信息(excel)
    uploadSubjectFro () {
      this.loading = true
      console.log('uploadSubjectFro')
      let file = this.$refs['uploadExc'].uploadFiles[0].raw
      let para = new FormData()
      para.append('file', file)
      apiFile.addImportSubject(para).then(res => {
        this.$refs['uploadExc'].clearFiles()
        this.loading = false
        console.log('addImportAirplane')
        console.log(res)
        if (res.data.result === 1000) {
          this.$message.success('批量导入科目信息成功！')
          this.getCollegeListFro()
        } else {
          this.$message.error(res.data.resultDesp)
        }
      })
      .catch(error => {
        this.loading = false
        console.log('error')
        this.$message.error(error)
        this.$refs['uploadExc'].clearFiles()
      })
    },
    // 向后台请求科类列表
    getSubjectListFro () {
      console.log('getSubjectListFro')
      let para = {}
      console.log(para)
      this.subjectList = []
      apiBus.getSubjectList(para).then(res => {
        this.loading = false
        console.log('getSubjectListFro 回参')
        console.log(res)
        if (res.data.result === 1000) {
          if (res.data.content.length > 0) {
            this.subjectList = res.data.content
          } else {
            this.$message.warning('没有任何科类信息，请先到科类管理页面添加科类信息！')
          }
        } else {
          this.$message.error(res.data.resultDesp)
        }
      })
      .catch(error => {
        console.log('失败')
        console.log(error)
        this.$message.error(error)
      })
    },
    // 向后台请求学院列表
    getCollegeListFro () {
      this.loading = true
      this.paginationVisible = false
      console.log('getCollegeListFro')
      let para = {}
      console.log(para)
      this.filterFormFro.tableData = []
      this.loading = false
      apiBus.getCollege(para).then(res => {
        this.loading = false
        console.log('getCollegeListFro 回参')
        console.log(res)
        if (res.data.result === 1000) {
          this.filterFormFro.tableData = res.data.content.list
          if (res.data.content.list.length > 0) {
            for (let i = 0; i < res.data.content.list.length; i++) {
              this.filterFormFro.tableData[i].index = i + 1
              this.filterFormFro.tableData[i].college = res.data.content.list[i].collegeName
            }
            this.$message.success('成功提取学院信息！')
          } else {
            this.$message.warning('没有任何学院信息')
          }
        } else {
          this.$message.error(res.data.resultDesp)
        }
      })
      .catch(error => {
        this.loading = false
        console.log('失败')
        console.log(error)
        this.$message.error(error)
      })
    },
    // 向后台发送增加学院信息
    addCollegeFro () {
      console.log('addCollegeFro')
      let para = {
        // subjectId: parseInt(this.addForm.subjectId),
        collegeName: this.addForm.college
        // subjectName: this.addForm.subjectName
      }
      console.log(para)
      apiBus.addCollege(para).then(res => {
        console.log('addCollegeFro 回参')
        console.log(res)
        if (res.data.result === 1000) {
          this.getCollegeListFro()
          this.$message.success('成功添加学院信息！')
          this.addVisable = false
        } else {
          this.$message.error(res.data.resultDesp)
        }
      })
      .catch(error => {
        console.log('失败')
        this.$message.error(error)
      })
    },
    // 向后台发送增加学院信息
    editCollegeFro () {
      console.log('editCollegeFro')
      let para = {
        collegeId: parseInt(this.editForm.collegeId),
        collegeName: this.editForm.college
        // subjectId: parseInt(this.editForm.subjectId),
        // subjectName: this.editForm.subjectName
      }
      console.log(para)
      apiBus.editCollege(para).then(res => {
        console.log('editCollegeFro 回参')
        console.log(res)
        if (res.data.result === 1000) {
          this.getCollegeListFro()
          this.$message.success('成功编辑学院信息！')
          this.editVisable = false
        } else {
          this.$message.error(res.data.resultDesp)
        }
      })
      .catch(error => {
        console.log('失败')
        this.$message.error(error)
      })
    },
    // 向后台发送删除专业信息
    deleteCollegeFro () {
      console.log('deleteCollegeFro')
      let para = {
        collegeId: parseInt(this.deleteForm.collegeId)
      }
      console.log(para)
      apiBus.deleteCollege(para).then(res => {
        console.log('deleteCollegeFro 回参')
        console.log(res)
        if (res.data.result === 1000) {
          this.getCollegeListFro()
          this.$message.success('成功删除该学院信息！')
          this.deleteVisable = false
        } else {
          this.$message.error(res.data.resultDesp)
        }
      })
      .catch(error => {
        console.log('失败')
        this.$message.error(error)
      })
    }
  },
  mounted () {
    this.tableWidth = document.body.scrollWidth - 259 - 20
  }
}
</script>
